﻿namespace ufida.u9.ait.openapi
{
    using System;
	using System.Collections.Generic;
	using ufida.u9.ait.openapi.utils;
	using UFIDA.U9.CBO.MFG.Enums;
	using UFIDA.U9.CBO.Pub.Controller;
	using UFIDA.U9.CBO.SCM.Item;
	using UFIDA.U9.MO.MO;
	using UFSoft.UBF.AopFrame;
	using UFSoft.UBF.Business;

	/// <summary>
	/// MOPickListModifySV partial 
	/// </summary>	
	public partial class MOPickListModifySV 
	{	
		internal BaseStrategy Select()
		{
			return new MOPickListModifySVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class MOPickListModifySVImpementStrategy : BaseStrategy
	{
		public MOPickListModifySVImpementStrategy() { }

		public override object Do(object obj)
		{						
			MOPickListModifySV bpObj = (MOPickListModifySV)obj;
			try
			{
                if (bpObj.Data == null || bpObj.Data.Count == 0)
                    throw new Exception("传入参数为空");
                List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

				foreach (var dto in bpObj.Data)
				{
					MO mo;
                    using (Session s = Session.Open())
					{
						mo = MO.Finder.Find($"DocNo='{dto.DocNo}'");
						if (mo == null)
						{
							throw new Exception($"单号:[{dto.DocNo}]不存在!");
						}
						else
						{
							//判断备料 新增/修改
							foreach (var dto1 in dto.PickList)
							{
								bool isAdd = true;
								if (dto1.ItemMaster == null || String.IsNullOrEmpty(dto1.ItemMaster.ItemCode))
									throw new Exception("传入物料为空!");

								foreach (var pick in mo.MOPickLists)
								{
									if (dto1.DocLineNO == 0) throw new Exception("DocLineNO 为空");
									if (pick.DocLineNO == dto1.DocLineNO)
									{
                                        //备料修改逻辑
                                        MOBase.ModifyPick(pick, dto1);
										isAdd = false;
										break;
									}
								}
								if (isAdd)
								{
                                    //备料新增逻辑
                                    MOBase.CreatePick(mo, dto1);
								}
							}
							//判断备料关闭
							foreach (var pick in mo.MOPickLists)
							{
								bool isClose = true;
								foreach (var dto1 in dto.PickList)
								{
									if (pick.ItemCode == dto1.ItemMaster.ItemCode)
									{
										isClose = false;
										break;
									}
								}

								if (isClose)
								{
									//关闭备料行,未找到字段
								}
							}
							
						}
                        s.Commit();
					}

                    //返回值
                    retlist.Add(new CommonArchiveDataDTOData
                    {
                        ID = mo.ID,
                        Code = mo.DocNo
                    });

                }

                return ResultUtils.success(bpObj, bpObj.Data, retlist);
            }
            catch(Exception ex)
			{
                return ResultUtils.error(bpObj, bpObj.Data, ex);
            }
		}
        
    }

	#endregion
	
	
}